/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sixviv
 */
public class SesionFiltro implements Filter{
    private ArrayList<String> urlList;
    private ServletContext context;

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String url = request.getServletPath();
        boolean allowedRequest = false;
        for(int i=0; i<urlList.size(); i++) {
            if(url.contains(urlList.get(i))) {
                allowedRequest = true;
                break;
            }
        }
        if (!allowedRequest) {
            if (request.getSession().getAttribute("user")==null) {
                    response.sendRedirect("index.jsp");
            }
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig config) throws ServletException {
                context = config.getServletContext();
        String urls = config.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");
        urlList = new ArrayList<String>();
        while (token.hasMoreTokens()) {
                urlList.add(token.nextToken());
        }
    }
}
